<?php

namespace Admin\Controller;

/**
 * 试题附件控制器
 *
 * @author zhiyuan
 *        
 */
class QuestionAttachmentsController extends AdminController {
	public function index() {
		$question_id = I ( 'id' );
		$question = D ( 'Questions' )->field ( true )->find ( $question_id );
		$map ['question'] = array (
				'eq',
				$question_id 
		);
		$questionattachments = $this->lists ( 'QuestionAttachments', $map, array (
				'order',
				'order' => 'asc',
				'id' => 'asc' 
		) );
		$this->assign ( 'question', $question );
		$this->assign ( 'questionattachments', $questionattachments );
		$this->meta_title = '附件管理';
		$this->display ();
	}
	public function addtext() {
		$question = I ( 'question' );
		$type = '1';
		if (IS_POST) {
			$questionattachments = D ( 'QuestionAttachments' );
			$data = $questionattachments->create ();
			if ($data) {
				if ($questionattachments->data ( $data )->add ()) {
					$this->success ( '新增成功', U ( 'index?id=' . $question ) );
				} else {
					$this->error ( '新增失败' );
				}
			} else {
				$this->error ( $questionattachments->getError () );
			}
		}
		$this->assign ( 'question', $question );
		$this->assign ( 'type', $type );
		$this->meta_title = '新增文本';
		$this->display ();
	}
	public function addimage() {
		$question = I ( 'question' );
		$this->assign ( 'question', $question );
		$this->meta_title = '新增图表';
		$this->display ();
	}
	public function edit($id) {
		if (IS_POST) {
			$questionattachments = D ( 'QuestionAttachments' );
			$data = $questionattachments->create ();
			if ($data) {
				if ($questionattachments->save ()) {
					$this->success ( '更新成功', U ( 'index?id=' . I ( 'question' ) ) );
				} else {
					$this->error ( '更新失败' );
				}
			} else {
				$this->error ( $questionattachments->getError () );
			}
		}
		$questionattachmentinfo = D ( 'QuestionAttachments' )->field ( true )->find ( $id );
		$this->assign ( 'questionattachmentinfo', $questionattachmentinfo );
		$this->meta_title = '编辑附件';
		$this->display ();
	}
	public function del() {
		$id = I ( 'id' );
		$question = I ( 'question' );
		$map ['id'] = array (
				'eq',
				$id 
		);
		if (D ( 'QuestionAttachments' )->where ( $map )->delete ()) {
			$this->success ( '删除成功', U ( 'index?id=' . $question ) );
		} else {
			$this->error ( '删除失败！' );
		}
	}
	public function upload($question = 0) {
		// 5分钟执行限制
		@set_time_limit ( 5 * 60 );
		
		// 设置
		$targetDir = 'Uploads/Plupload/' . time_format ( NOW_TIME, 'Ymd' );
		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds
		                        
		// 创建目标文件夹
		if (! file_exists ( $targetDir )) {
			@mkdir ( $targetDir );
		}
		
		// 原始文件名
		$originalfile = $_FILES ["file"] ["name"];
		// Get a file name
		if (isset ( $_REQUEST ["name"] )) {
			$fileName = $_REQUEST ["name"];
		} elseif (! empty ( $_FILES )) {
			$fileName = $_FILES ["file"] ["name"];
		} else {
			$fileName = uniqid ( "file_" );
		}
		$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
		
		// Chunking might be enabled
		$chunk = isset ( $_REQUEST ["chunk"] ) ? intval ( $_REQUEST ["chunk"] ) : 0;
		$chunks = isset ( $_REQUEST ["chunks"] ) ? intval ( $_REQUEST ["chunks"] ) : 0;
		
		// Remove old temp files
		if ($cleanupTargetDir) {
			if (! is_dir ( $targetDir ) || ! $dir = opendir ( $targetDir )) {
				die ( '{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}' );
			}
			
			while ( ($file = readdir ( $dir )) !== false ) {
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
				
				// If temp file is current file proceed to the next
				if ($tmpfilePath == "{$filePath}.part") {
					continue;
				}
				
				// Remove temp file if it is older than the max age and is not the current file
				if (preg_match ( '/\.part$/', $file ) && (filemtime ( $tmpfilePath ) < time () - $maxFileAge)) {
					@unlink ( $tmpfilePath );
				}
			}
			closedir ( $dir );
		}
		
		// Open temp file
		if (! $out = @fopen ( "{$filePath}.part", $chunks ? "ab" : "wb" )) {
			die ( '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}' );
		}
		
		if (! empty ( $_FILES )) {
			if ($_FILES ["file"] ["error"] || ! is_uploaded_file ( $_FILES ["file"] ["tmp_name"] )) {
				die ( '{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}' );
			}
			
			// Read binary input stream and append it to temp file
			if (! $in = @fopen ( $_FILES ["file"] ["tmp_name"], "rb" )) {
				die ( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
			}
		} else {
			if (! $in = @fopen ( "php://input", "rb" )) {
				die ( '{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}' );
			}
		}
		
		while ( $buff = fread ( $in, 4096 ) ) {
			fwrite ( $out, $buff );
		}
		
		@fclose ( $out );
		@fclose ( $in );
		
		// Check if file has been uploaded
		
		if (! $chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off
			rename ( "{$filePath}.part", $filePath );
			// 存入附件表
			$image = str_replace ( '\\', '/', $filePath );
			$questionattachment = D ( 'QuestionAttachments' );
			$questionattachment->create ();
			$data ['text'] = substr_replace ( $originalfile, '', - 4 );
			$data ['image'] = $image;
			$data ['question'] = $question;
			$data ['answer_rows'] = 0;
			$data ['create_time'] = NOW_TIME;
			$data ['update_time'] = NOW_TIME;
			$data ['type'] = 0;
			$data ['status'] = 1;
			$questionattachment->data ( $data )->add ();
		}
		// Return Success JSON-RPC response
		die ( '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}' );
	}
}

?>